package com.zzh.myapplication.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import net.icarplus.car.R;
import net.icarplus.car.app.MyApplication;
import net.icarplus.car.constant.Content;
import net.icarplus.car.constant.UrlValues;
import net.icarplus.car.manager.BaseActivity;
import net.icarplus.car.tools.HttpService;
import net.icarplus.car.tools.ImageCacheManager;
import net.icarplus.car.tools.ToolBarHelper;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 项目名称：icarplus-car-android
 * 类描述：
 * 创建人：Gophy
 * 创建时间：16/4/6 16:02
 * 修改人：Gophy
 * 修改时间：16/4/6 16:02
 * 修改备注：
 */
public class PersonMsgActivity extends BaseActivity {

    private Toolbar toolbar;
    private PopupWindow headPopupWindow;
    private TextView photosTxt, takePhotoTxt, phoneTxt, moneyTxt;

    private LinearLayout person_msg_head_lilayout;

    public static final int REQ_FROM_PHOTO = 1;
    public static final int REQ_FROM_CAMERA = 2;
    public static final int REQ_FROM_PHOTOEDIT = 3;
    public static final int REQ_FROM_SETUP = 4;

    private static final int CROP_BIG_PICTURE = 0x12;

    private SimpleDraweeView person_msg_head_imgv;

    @Override
    public void setContent() {
        setContentView(R.layout.activity_person_msg);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ToolBarHelper.setNormalTitleAndBack(this, toolbar, getString(R.string.person_msg));
        person_msg_head_lilayout = (LinearLayout) findViewById(R.id.person_msg_head_lilayout);

        person_msg_head_imgv = (SimpleDraweeView)findViewById(R.id.person_msg_head_imgv);
    }

    @Override
    public void initComponent() {

    }

    @Override
    public void setListener() {
        person_msg_head_lilayout.setOnClickListener(this);
    }

    @Override
    public void onAfterInit() {

        if (MyApplication.acctResultInfo != null) {
            String headUrl = UrlValues.CAR_IMG_ID + MyApplication.acctResultInfo.headImgUrl;
//            ImageCacheManager.setImageBackgroundToImageView(PersonMsgActivity.this,
//                    person_msg_head_imgv, headUrl, R.mipmap.icon_mine_default_person);
            person_msg_head_imgv.setImageURI(Uri.parse(headUrl));
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.person_msg_head_lilayout:
                openPopupWindow();
                break;
            case R.id.pupwindow_photos_txt:
                headPopupWindow.dismiss();
                photoFormAlbum();
                break;
            case R.id.pupwindow_take_photo_txt:
                headPopupWindow.dismiss();
                photoFormCamera();
                break;
            default:
                break;
        }

    }

    //从相机中获得照片
    private void photoFormCamera() {
        Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(getExternalCacheDir(), "IMG" + "head" + ".png");
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        startActivityForResult(intentCamera, REQ_FROM_CAMERA);
    }

    private void photoFormAlbum() {
        Intent mIntent = new Intent(Intent.ACTION_GET_CONTENT);
        mIntent.addCategory(Intent.CATEGORY_OPENABLE);
        mIntent.setType("image/*");
        startActivityForResult(mIntent, REQ_FROM_PHOTO);
    }

    private void openPopupWindow() {
        if (headPopupWindow == null) {
            View popupLayout = getLayoutInflater().inflate(R.layout.popupwindow_person_msg, null);
            photosTxt = (TextView) popupLayout.findViewById(R.id.pupwindow_photos_txt);
            takePhotoTxt = (TextView) popupLayout.findViewById(R.id.pupwindow_take_photo_txt);
            headPopupWindow = new PopupWindow(popupLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            headPopupWindow.setFocusable(true);
            headPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            //防止虚拟软键盘被弹出菜单遮住
            headPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            //设置PopupWindow的弹出和消失效果
            headPopupWindow.setAnimationStyle(R.style.AnimBottom);
            headPopupWindow.showAtLocation(findViewById(R.id.person_msg_lilayout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            popupLayout.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // TODO Auto-generated method stub
                    headPopupWindow.dismiss();
                    return true;
                }
            });
            photosTxt.setOnClickListener(this);
            takePhotoTxt.setOnClickListener(this);
        } else {
            headPopupWindow.showAtLocation(findViewById(R.id.person_msg_lilayout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            System.out.println("fdfa::" + msg.what);
            switch (msg.what) {
                case 0:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    String url = UrlValues.CAR_IMG_ID + MyApplication.acctResultInfo.getHeadImgUrl() + "&" + MyApplication.acctResultInfo.getFileName();
                    Log.e("Long", "提交后头像URL：" + url);

                    ImageCacheManager.setImageBackgroundToImageView(PersonMsgActivity.this,
                            person_msg_head_imgv, url, R.mipmap.icon_mine_default_person);
//				JdaApplication.mineFragment.downLoadPhoto();
//                    PublicService.queryUserInfo(PersonMsgActivity.this, handler, JdaApplication.acctResultInfo.getMobile());
                    break;
                case 1000:
//                    String url = UrlValues.CAR_IMG_ID + MyApplication.acctResultInfo.getHeadImgUrl() + "&" + MyApplication.acctResultInfo.getFileName();
//                    Log.e("Long", "提交后头像URL：" + url);
//                    Log.e("Long", "Image"+JdaApplication.acctResultInfo.getHeadImgUrl());
//                    String path = Content.SDCARDIMAGE+MD5Utils.getMD5(url)+".png";
//                    File file = new File(path);//头像图片
//                    Log.e("Long", "提交后文件地址:"+path);
//                    if(file.exists()){
//                        file.delete();//删除旧头像
//                    }
//                    setSp(JdaApplication.acctResultInfo.getMobile(), JdaApplication.acctResultInfo.getCustId());
//                    downLoadPhoto();
//                    if(JdaApplication.mineFragment!=null){
//                        JdaApplication.mineFragment.query();
//                        JdaApplication.mineFragment.downLoadPhoto();
//                        Log.e("Long", "有进来刷新");
//                    }

                    break;
                case 1003:
//                    WalletResultInfo resultInfo = (WalletResultInfo)msg.obj;
//                    refreshUI(resultInfo);
                    break;
                case 1:
                    String message = (String) msg.obj;
                    showAlerDialog("提示", message, null);
                    break;
                case 30000:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    Log.e("Long", "上传失败");
                    break;
                default:
                    break;
            }
        }
    };


    private int type = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK)
            return;
        if (requestCode == REQ_FROM_CAMERA) {
            type = REQ_FROM_CAMERA;
            File f = new File(getExternalCacheDir(), "IMG" + "head" + ".png");
            if (!f.exists()) {
                f = new File(getExternalCacheDir(), "IMG" + "head" + ".png");
            }
            if (f.exists())
                toCutting(f);
        }
        if (requestCode == REQ_FROM_PHOTO) { // 从相簿中返回的照片
            type = REQ_FROM_PHOTO;
            Uri uri = data.getData(); // 返回的是一个Uri
            String path = uri.getPath();
            File f = new File(path);
            if (!f.exists()) {
                path = GetPath(uri);
                f = new File(path);
            }
            if (f.exists())
                toCutting(f);//将真实照片文件地址传入
        }
        if (requestCode == REQ_FROM_PHOTOEDIT) { // 从图像编辑中返回
        }
        if (requestCode == CROP_BIG_PICTURE) {//裁切
            File f = new File(Content.SDCARDIMAGEUPLOADCACHE, "head.png");
            if (f.length() > 0) {
                UpdateUI(f);
            }
        }
    }

    private void toCutting(File f) {
        if (f != null) {
            if (isImageFile(f.getName())) {
                File newf = new File(Content.SDCARDIMAGEUPLOADCACHE, "head.png");
                CropImageUri(Uri.fromFile(f), Uri.fromFile(newf), CROP_BIG_PICTURE);
            } else {
                Log.e("Long", "照片文件格式不对");
            }
        }
    }

    private String GetPath(Uri uri) {
        //
        String path = uri.getPath();
        File mfile = new File(path);
        if (mfile.exists())
            return mfile.getPath();
        try {
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String s = cursor.getString(column_index);
//			cursor.close();
            return (s);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return (null);
    }

    private void CropImageUri(Uri uri, Uri outuri, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 120);
        intent.putExtra("outputY", 120);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outuri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

    private void UpdateUI(File f) {
        if (f != null) {
            if (isImageFile(f.getName())) {
                submitHead(f.getPath());
            } else {
                Log.e("Long", "文件格式不对");
            }
        }

    }


    private boolean isImageFile(String filename) {
        String s = filename.toLowerCase();
        return (s.endsWith(".jpeg") ||
                s.endsWith(".jpg") ||
                s.endsWith(".gif") ||
                s.endsWith(".bmp") ||
                s.endsWith(".png")
        );
    }


    Dialog dialog;

    public void submitHead(String path) {
        dialog = new Dialog(this, R.style.loadingDialog);
        dialog.setContentView(R.layout.dialog_loading);
        dialog.show();
        Log.e("Long", "path:" + path);
        Map<String, String> map = new HashMap<String, String>();
//			if(JdaApplication.acctResultInfo!=null){
        map.put("mobile", "13976448965");
        map.put("relaTable", "c_cust");
        upLoadFile(UrlValues.ADD_ACCOUNT_HEAD_IMAGE_URL, map, path, handler, 0);

    }


    public static void upLoadFile(final String url, final Map<String, String> map, final String path, final Handler handler, final int messageId) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    String result = HttpService.HttpsPostData(url, map, new File(path));
                    if (result != null && result.indexOf("10000") != -1) {
                        handler.sendEmptyMessage(messageId);
                    } else {
                        handler.obtainMessage(30000, "上传失败").sendToTarget();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    handler.obtainMessage(30000, "上传失败").sendToTarget();
                }
            }
        }).start();
        ;
    }

//    public void downLoadPhoto() {
//        if (JdaApplication.acctResultInfo != null) {
//            String url = Content.URLDOWNLOADIMAGE
//                    + JdaApplication.acctResultInfo.getHeadImgUrl() + "&"
//                    + JdaApplication.acctResultInfo.getFileName();
//            Log.e("Long", "url" + url);
//            Log.e("Long", "JdaApplication.acctResultInfo.getHeadImgUrl()"
//                    + JdaApplication.acctResultInfo.getHeadImgUrl());
//            Log.e("Long", "JdaApplication.acctResultInfo.getFileName()"
//                    + JdaApplication.acctResultInfo.getFileName());
//            ImageUtil.asyncImageLoad(headImagv, url, Content.SDCARDIMAGE,
//                    new ImageLoadSuccessListener() {
//
//                        @Override
//                        public void onLoadSuccess(Uri uri) {
//                            // TODO Auto-generated method stub
//                            Bitmap bitmap = BitmapFactory.decodeFile(uri
//                                    .getPath());
//                            if (bitmap != null) {
//                                headImagv.setImageBitmap(DecorationImageUtil
//                                        .toRoundCorner(bitmap, 2));// 提交成功，用ImageView显示出来
//                                bitmap.recycle();
//                                bitmap = null;
//                            }
//
//                        }
//
//                    });
//        }
//    }
}
